package business

import (
    "os"
    "strconv"

    "git.inspur.com/x/xxl-job-go-core/src/core/executor"
    "git.inspur.com/x/xxl-job-go-core/src/core/executor_impl"
    "git.inspur.com/x/xxl-job-go-core/src/core/handler"
    "git.inspur.com/x/xxl-job-go-core/src/core/log4xxl"
    xxlModels "git.inspur.com/x/xxl-job-go-core/src/core/models"
    "git.inspur.com/x/xxl-job-go-core/src/hessian"
)

func ConfigCronJob(jobCenterAddress string) {
    appName := "fcs"
    port := 9995
    conf := hessian.Config{
        ServerAddress:                  jobCenterAddress,
        ServerAppname:                  appName,
        ServerExecutorip:               "",
        ServerExecutorport:             port,
        ServerAccestoken:               "",
        ServerLogpath:                  "/data/applogs/xxl-job/jobhandler",
        ServerExecutorlogretentiondays: -1,
        ServerRegistgroup:              "EXECUTOR",
        ServerRegistkey:                appName,
        ServerRegistvalue:              os.Getenv("POD_IP") + ":" + strconv.Itoa(port),
    }
    var bssJobHandler BssJobHandler
    _ = executor_impl.SetJobHandler("bssJobHandler", &bssJobHandler)
    jobInfo := xxlModels.XxlJobInfoCore{
        // jobcenter使用的是utc时间，比北京时间晚8个小时，所以需要提前8个小时执行
        JobCron:                "0 0 17 * * ?",
        InstanceId:             "fcs-bss",
        Creator:                appName,
        ExecutorHandler:        "bssJobHandler",
        ExecutorParam:          "",
        ExecutorTimeout:        120,
        ExecutorFailRetryCount: 3,
    }
    createJob(jobInfo, conf.ServerAddress, appName)
    go executor.Start(conf, 120)
}

func createJob(jobInfo xxlModels.XxlJobInfoCore, address, appName string) {
    res := executor_impl.GetJob(address, appName, jobInfo.InstanceId)
    if len(res) > 0 {
        return
    }
    executor_impl.CreateJob(jobInfo, address, appName)
}

type BssJobHandler struct {
    handler.HandlerModel
}

func (d *BssJobHandler) Execute(param string, xxlLogger log4xxl.XxlJobLogger) *xxlModels.ReturnT {
    go func() {
        err := ReportDaily()
        if err != nil {
            _ = logger.Error("handleReportBss: report error, %s", err.Error())
        } else {
            logger.Info("Report to Bss success")
        }
    }()
    xxlLogger.Log("receive bss job ")
    return xxlModels.NewReturnT(xxlModels.SUCCESS_CODE, param)
}

func (t *BssJobHandler) Init() error {
    return nil
}
func (t *BssJobHandler) Destroy() error {
    return nil
}
